using System.Reflection.Metadata.Ecma335;
using Microsoft.AspNetCore.Mvc;
using ShopForWeb.Dto.ViewModels;
using ShopForWeb.Dto.AjaxModels;
using ShopForWeb.Service;
using ShopForWeb.UI.Filters;

namespace ShopForWeb.UI.Controllers.Admin;
[Area("admin")]
[Route("[area]/managers")]

public class ManagerController : Controller
{
  private ManagerService _service;
  public ManagerController(ManagerService service)
  {
    _service = service;

  }
  [ManagerInfoFilter]
  [HttpGet("{page?}/{pageSize?}/{key?}")]
  public async Task<IActionResult> GetPageAsync([ModelBinder(Name = "page")] int page = 1, [ModelBinder(Name = "pageSize")] int pageSize = 15, [ModelBinder(Name = "key")] string key = "")
  {
    var managers = await _service.GetByPageAsync((page - 1) * pageSize, pageSize, key);
    var total = await _service.GetCountAsync(key);
    PageBarViewModel pagebar = new PageBarViewModel(page, pageSize, total);
    ViewBag.Data = new
    {
      Managers = managers,
      PageBar = pagebar
    };
    return View();
  }
  [HttpPut("info")]
  public async Task<IActionResult> AddNewAsync(ManagerViewModel pvm)
  {
    int result = await _service.AddNewAsync(pvm);
    if (result > 0)
      return Json(new ResponseAjaxModel()
      {
        Status = 0,
        Message = "添加成功"
      });
    else
      return Json(new ResponseAjaxModel()
      {
        Status = 1,
        Message = "添加失败"
      });
  }


  [HttpGet("info/{managerID}")]
  [ManagerInfoFilter]
  public async Task<IActionResult> GetByIDAsync(int managerID)
  {
    var p = await _service.GetByIDAsync(managerID);
    ViewBag.Data = p;
    return View();
  }
  [HttpPost("info")]
  [ManagerInfoFilter]
  public async Task<IActionResult> ModifyAsync(ManagerViewModel pvm)
  {
    int result = await _service.ModifyAsync(pvm);
    if (result > 0)
      return Json(new ResponseAjaxModel()
      {
        Status = 0,
        Message = "修改成功"
      }
      );
    else
      return Json(new ResponseAjaxModel()
      {
        Status = 1,
        Data = "修改失败"
      });
  }

  [HttpDelete("info/{managerID}")]
  public async Task<IActionResult> RemoveAsync(int managerID)
  {
    int result = await _service.RemoveAsync(managerID);
    if (result > 0)
      return Json(new ResponseAjaxModel
      {
        Status = 0,
        Message = "删除成功"
      });
    else
      return Json(new ResponseAjaxModel
      {
        Status = 1,
        Message = "删除失败"
      });
  }

  [HttpGet("password")]
  public IActionResult ModifyPassword()
  {
    return View();
  }

  [HttpPost("logout")]
  public IActionResult Logout()
  {
    this.HttpContext.Session.Remove("manager");
    return Json(new ResponseAjaxModel()
    {
      Status = 0,
      Message = ""
    });
  }

}
